package com.seednia.module.core.search;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;

import com.seednia.foundation.framework.dto.AbstractRecord;
import com.seednia.foundation.framework.service.RequestContext;
import com.seednia.foundation.framework.service.ServiceContainer;
import com.seednia.module.core.search.service.ISearchService;

/**
 * Aspect Class that indexe when insert* method is called on a service
 * @author Young Suk Ahn
 *
 */
@Aspect
public class SearchIndexerAspect implements Ordered {

	protected ISearchService service = null;  
	
	private static final Log logger = LogFactory
			.getLog(SearchIndexerAspect.class);
	
	@Override
	public int getOrder() {
		// TODO Auto-generated method stub
		return 0;
	}
	

	public ISearchService getSearchEngineService() {
		if (service == null) {
			service = ServiceContainer.getInstance().getByType(ISearchService.class);
		}
		return service;
	}
	public void setSearchEngineService(ISearchService service) {
		this.service = service;
	}
	
	
	@After("execution(* com.ecologixsystem.component.core.command.CommandService.execute(com.ecologixsystem.framework.server.ALT_RequestContext, ..))")
	public void indexForSearch(JoinPoint joinPoint)
	{
		RequestContext requestContext = (RequestContext) joinPoint.getArgs()[0];
		AbstractRecord record = (AbstractRecord) joinPoint.getArgs()[1];
		
		logger.debug("at indexForSearch");
		try {
			getSearchEngineService().index(requestContext, record);
		} catch (Exception e) {
			logger.warn(e);
		}
		
	}

}
